package com.online.fund.schedule;

import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.online.fund.service.HolidayService;
import com.online.fund.service.SharesMoniterService;
import com.online.fund.util.DateUtils;

/**
 * 
 * <p>Description: 定时执行任务</p>
 * sample: https://www.jianshu.com/p/ef18af5a9c1d
 */
@Component
public class ScheduledTask {
	
	private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);  
	  
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss"); 
    
    private LocalTime morningStartTime = LocalTime.of(9, 30);
    private LocalTime morningEndTime = LocalTime.of(11, 30);
    private LocalTime afternoonStartTime = LocalTime.of(13, 30);
    private LocalTime afternoonEndTime = LocalTime.of(15, 0);
    
    @Resource
    private SharesMoniterService sharesMoniterService;
    
    @Resource
    private HolidayService holidayService;
    
    /** 
     * 每隔5秒执行, 单位：ms。 
     */  
//    @Scheduled(fixedRate = 5000)  
    public void testFixRate() {  
        System.out.println("我每隔5秒冒泡一次：" + dateFormat.format(new Date()));  
    }  
  
//    @Scheduled(cron = "0 0 1 * * ?")    //每天凌晨1点执行  
    public void testMyBatis() {  
        System.out.println("我每天凌晨1点开始执行");  
    }    

    @Scheduled(cron = "0 */1 9-22 * * MON-FRI")    //周一到周五下午15点30执行  
    public void moniterSharesPrice() {  
    	if (checkTaskDatetime()) {
    		sharesMoniterService.moniterSharesPrice();
    	}
    }
    
    @Scheduled(cron = "0 */1 9-22 * * MON-FRI")    //周一到周五下午15点30执行  
    public void sendEmailNotify() {  
    	if (checkTaskDatetime()) {
    		try {
				sharesMoniterService.sendEmailNotify();
			} catch (Exception e) {
				logger.error("发送邮件失败：", e);
			}
    	}
    }

    /**
     * 非节假日，9:30--11:30，13:30--15:00运行
     * @return
     */
	private boolean checkTaskDatetime() {
		LocalTime time = LocalTime.now();
		boolean flag = false;
		if ((time.isAfter(morningStartTime) && time.isBefore(morningEndTime)) || (time.isAfter(afternoonStartTime) && time.isBefore(afternoonEndTime))) {
			System.out.println("定时任务在指定时间段内运行: " + time.toString());
			flag = true;
			
			// 公共假期
			String date = DateUtils.getCurrentDate();
			if (holidayService.getHolidays().contains(date)) {
				flag = false;
			}
		}
		return flag;
	}
}
